"""The base Controller API

This module provides the BaseController for all controllers to subclass, as
well as functions and objects for use by those controllers.
"""
import re

from pylons import c, cache, config, g, request, response, session
from pylons.controllers import WSGIController
from pylons.decorators import jsonify, validate
from pylons.controllers.util import abort, etag_cache, redirect_to
from pylons.i18n import _, ungettext, N_
from pylons.templating import render

import eshop.lib.helpers as h
import eshop.model as model

def in_role(*roles):
    def check_roles(f):
        def new_f(action, id=None):
            #check here
            return f(action, id) if id != None else f(action)
                
        return new_f
    return check_roles

def sanitize_name_to_url(name): 
    """
    Borrowed from Wordpress
$name = strtolower( $name );
$name = preg_replace('/&.+?;/', '', $name); // kill entities
$name = str_replace( '_', '-', $name );
$name = preg_replace('/[^a-z0-9\s-.]/', '', $name);
$name = preg_replace('/\s+/', '-', $name);
$name = preg_replace('|-+|', '-', $name);
$name = trim($name, '-');
6:0
    """
    name = name.lower()
    name = re.sub(r'&.+?;', '', name)
    name = name.replace('_', '-') 
    name = re.sub(r'[^a-z0-9\s-]', '', name)
    name = re.sub(r'\s+', '-', name)
    name = name.strip('-')
    return name


class BaseController(WSGIController):
    
    
    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method the
        # request is routed to. This routing information is available in
        # environ['pylons.routes_dict']
        
         # Refresh database session
        model.resync()
        # Insert any code to be run per request here. The Routes match
        # is under environ['pylons.routes_dict'] should you want to check
        # the action or route vars here
        
        res = WSGIController.__call__(self, environ, start_response)     
        model.flush_all()
        return res
#        try:
#            return WSGIController.__call__(self, environ, start_response)
#        finally:
#            model.Session.remove()
# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
           or __name == '_']
